package com.majorty.mail.service.impl;

import com.majorty.mail.entity.FileAttachEntity;
import com.majorty.mail.service.EmailService;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author zhangshuai
 * @date 2019-08-31 17:37
 */
@Service
@Configuration
public class EmailServiceImpl implements EmailService {
    //邮件的发送者
    @Value("${spring.mail.username}")
    private String from;
    //注入MailSender
    @Autowired
    private JavaMailSender javaMailSender;
    //发送邮件的模板引擎
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public void sendMessageMail(Object params, String title, String templateName){
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(InternetAddress.parse("test@atguigu.com"));//发送给谁
            mimeMessageHelper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题
            Map<String,Object> model = new HashMap<>();
            model.put("params",params);
            try{
                Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
                try{
                    String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
                    mimeMessageHelper.setText(text,true);
                    javaMailSender.send(mimeMessage);
                }catch (TemplateException e){
                    e.printStackTrace();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (MessagingException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * logo路径
     */
    private static final String LOGO_FILE_PATH = "templates/img/logo.png";
    private static Logger logger = LoggerFactory.getLogger(EmailService.class);



    @Override
    public void sendMail(String title, List<String> to, List<String> copyTo, String templatePath, Map<String, Object> model, List<FileAttachEntity> fileAttachList) {
        if (StringUtils.isEmpty(templatePath)){
            logger.error("=> 邮件模板路径为空！");
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            //邮件发送人(账号)
            helper.setFrom(from);
            //邮件接收人(账号)
            if (CollectionUtils.isNotEmpty(to)){
                String toStr = StringUtils.join(to.toArray(), ",");
                InternetAddress[] toList = InternetAddress.parse(toStr);
                helper.setTo(toList);
            }
            //邮件抄送人(账号)
            if (CollectionUtils.isNotEmpty(copyTo)){
                String copyToStr = StringUtils.join(copyTo.toArray(), ",");
                InternetAddress[] copyToList = InternetAddress.parse(copyToStr);
                helper.setCc(copyToList);
            }
            //替换邮件模板生成邮件正文
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath);
            String context = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
            helper.setText(context,true);
            //图片logo
            ClassPathResource image = new ClassPathResource(LOGO_FILE_PATH);
            helper.addInline("logo",image);
            //附件
            if (CollectionUtils.isNotEmpty(fileAttachList)){
                for (FileAttachEntity fileAttach : fileAttachList) {
                    if (StringUtils.isNotEmpty(fileAttach.getFileName()) && fileAttach.getFileStream().length > 0) {
                        helper.addAttachment(fileAttach.getFileName(), new ByteArrayResource(fileAttach.getFileStream()));
                    }else {
                        logger.info("附件url【"+fileAttach.getFileUrl()+"】对应的附件文件为空");
                    }
                }
            }
            //邮件标题
            helper.setSubject(title);
            //发送日期
            helper.setSentDate(new Date());
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void sendMail(String title, List<String> to, List<String> copyTo, String context, List<FileAttachEntity> fileAttachList) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            //邮件发送人(账号)
            helper.setFrom(from);
            //邮件接收人(账号)
            if (CollectionUtils.isNotEmpty(to)){
                String toStr = StringUtils.join(to.toArray(), ",");
                InternetAddress[] toList = InternetAddress.parse(toStr);
                helper.setTo(toList);
            }
            //邮件抄送人(账号)
            if (CollectionUtils.isNotEmpty(copyTo)){
                String copyToStr = StringUtils.join(copyTo.toArray(), ",");
                InternetAddress[] copyToList = InternetAddress.parse(copyToStr);
                helper.setCc(copyToList);
            }
            //邮件正文
            helper.setText(context,true);
            //图片logo
            if(StringUtils.contains(context,"cid:logo")){
                ClassPathResource image = new ClassPathResource(LOGO_FILE_PATH);
                helper.addInline("logo",image);
            }
            //附件
            if (CollectionUtils.isNotEmpty(fileAttachList)){
                for (FileAttachEntity fileAttach : fileAttachList) {
                    if (StringUtils.isNotEmpty(fileAttach.getFileName()) && fileAttach.getFileStream().length > 0) {
                        helper.addAttachment(fileAttach.getFileName(), new ByteArrayResource(fileAttach.getFileStream()));
                    }else {
                        logger.info("附件url【"+fileAttach.getFileUrl()+"】对应的附件文件为空");
                    }
                }
            }
            //邮件标题
            helper.setSubject(title);
            //发送日期
            helper.setSentDate(new Date());
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            logger.info("==> 邮件发送失败");
            e.printStackTrace();
        }
    }
}
